package com.ruoyi.teaching.service.impl;

import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.teaching.dto.AddInterviewMasteryDTO;
import com.ruoyi.teaching.domain.YaInterviewMasteryDetail;
import com.ruoyi.teaching.service.IYaInterviewMasteryDetailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.teaching.mapper.YaInterviewMasteryMapper;
import com.ruoyi.teaching.domain.YaInterviewMastery;
import com.ruoyi.teaching.service.IYaInterviewMasteryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 面试掌握情况记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-14
 */
@Service
public class YaInterviewMasteryServiceImpl implements IYaInterviewMasteryService
{
    @Autowired
    private YaInterviewMasteryMapper yaInterviewMasteryMapper;

    @Autowired
    private IYaInterviewMasteryDetailService yaInterviewMasteryDetailService;
    /**
     * 查询面试掌握情况记录
     *
     * @param id 面试掌握情况记录主键
     * @return 面试掌握情况记录
     */
    @Override
    public YaInterviewMastery selectYaInterviewMasteryById(Long id)
    {
        return yaInterviewMasteryMapper.selectYaInterviewMasteryById(id);
    }

    /**
     * 查询面试掌握情况记录列表
     *
     * @param yaInterviewMastery 面试掌握情况记录
     * @return 面试掌握情况记录
     */
    @Override
    public List<YaInterviewMastery> selectYaInterviewMasteryList(YaInterviewMastery yaInterviewMastery)
    {
        return yaInterviewMasteryMapper.selectYaInterviewMasteryList(yaInterviewMastery);
    }

    /**
     * 新增面试掌握情况记录
     *
     * @param addInterviewMasteryDTO 面试掌握情况记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertYaInterviewMastery(AddInterviewMasteryDTO addInterviewMasteryDTO)
    {
        //["1,1", "2,2", "3,3", "3,4", "3,5"]
        List<String> selectedInterviewList = addInterviewMasteryDTO.getSelectedInterviewList();
        //selectedInterviewList->map<questionId,掌握程度集合>
        Map<String, Set<String>> questionDegreeMap = new HashMap<>();
        for (String str : selectedInterviewList) {
            // 1(questionId),1(degree)
            String[] split = str.split(",");
            String questionId = split[0];
            String degree = split[1];
            //判断当前面试题是否存在
            Set<String> questionDegreeSet = questionDegreeMap.getOrDefault(questionId, new HashSet<>());
            questionDegreeSet.add(degree);

            questionDegreeMap.put(questionId, questionDegreeSet);
        }
        Date nowDate = DateUtils.getNowDate();
        //面试题总分
        long totalScore = 0l;

        //questionDegreeMap -> interviewMasteryDetails
        List<YaInterviewMasteryDetail> interviewMasteryDetails = new ArrayList<>(selectedInterviewList.size());
        for (Map.Entry<String, Set<String>> entry : questionDegreeMap.entrySet()) {
            //questionId
            Long questionId = Long.valueOf(entry.getKey());
            Set<String> questionDegreeSet = entry.getValue();

            String degree = StringUtils.join(questionDegreeSet, ",");

            YaInterviewMasteryDetail yaInterviewMasteryDetail = YaInterviewMasteryDetail.builder().questionId(questionId).degree(degree)
                    .score(getScore(questionDegreeSet))
                    .userId(addInterviewMasteryDTO.getUserId())
                    .createTime(nowDate)
                    .build();
            totalScore+=yaInterviewMasteryDetail.getScore();
            interviewMasteryDetails.add(yaInterviewMasteryDetail);
        }
        //计算平均分
        long avgScore = totalScore / interviewMasteryDetails.size();

        //1.新增1方
        addInterviewMasteryDTO.setCreateTime(nowDate);
        addInterviewMasteryDTO.setAvgScore(avgScore);
        addInterviewMasteryDTO.setCommunicationScore((long) addInterviewMasteryDTO.getCommunicationMastery().split(",").length);
        yaInterviewMasteryMapper.insertYaInterviewMastery(addInterviewMasteryDTO);
        Long interviewMasteryId = addInterviewMasteryDTO.getId();
        //2.新增n方（维护关系）
        for (YaInterviewMasteryDetail interviewMasteryDetail : interviewMasteryDetails) {
            interviewMasteryDetail.setInterviewMasteryId(interviewMasteryId);
        }
        return yaInterviewMasteryDetailService.saveBatch(interviewMasteryDetails) ? 1 : 0;
    }

    private Long getScore(Set<String> questionDegreeSet) {
        long result = 0L;
        //遍历questionDegreeSet，如果1返回0，2返回1，其他累加2分
        for (String str : questionDegreeSet) {
            if ("1".equals(str)) {
                return 0L;
            }
            if ("2".equals(str)) {
                return 1L;
            }
            result+=2L;
        }
        return result;
    }

    /**
     * 修改面试掌握情况记录
     *
     * @param yaInterviewMastery 面试掌握情况记录
     * @return 结果
     */
    @Override
    public int updateYaInterviewMastery(YaInterviewMastery yaInterviewMastery)
    {
        yaInterviewMastery.setUpdateTime(DateUtils.getNowDate());
        return yaInterviewMasteryMapper.updateYaInterviewMastery(yaInterviewMastery);
    }

    /**
     * 批量删除面试掌握情况记录
     *
     * @param ids 需要删除的面试掌握情况记录主键
     * @return 结果
     */
    @Override
    public int deleteYaInterviewMasteryByIds(Long[] ids)
    {
        return yaInterviewMasteryMapper.deleteYaInterviewMasteryByIds(ids);
    }

    /**
     * 删除面试掌握情况记录信息
     *
     * @param id 面试掌握情况记录主键
     * @return 结果
     */
    @Override
    public int deleteYaInterviewMasteryById(Long id)
    {
        return yaInterviewMasteryMapper.deleteYaInterviewMasteryById(id);
    }
}
